import { createAsyncThunk, createSlice } from "@reduxjs/toolkit";
import type { ActionReducerMapBuilder, AsyncThunk, PayloadAction } from "@reduxjs/toolkit";
import type { AsyncThunkConfig } from "@reduxjs/toolkit/dist/createAsyncThunk";
import { AddOrUpdateCartParams, Cart, CartResult } from "@/type/CartType";
import { addCartAPI, deleteCartAPI, fetchCartListAPI, updateCartAPI } from "@/api/cartAPI";

type  ChangeCheckedActionType = {
   type: string
   payload: { goods_id: number, checked: boolean }
}

type DeleteGoodActionType = {
   type: string
   payload: number
}

type InitialState = {
   cartList: Cart[],
   cartTotal: number
}

const initialState: InitialState = {
   cartList: [],
   cartTotal: 0,
};

/**
 * @description 获取购物车商品列表的asyncThunk函数
 * */
export const fetchCartListThunk: AsyncThunk<CartResult, void, AsyncThunkConfig> = createAsyncThunk("fetchCartListThunk", async (_: void, { rejectWithValue }) => {
   try {
      const { data } = await fetchCartListAPI();
      data.list.forEach(item => item.checked = true);
      return data;
   } catch (error: any) {
      return rejectWithValue(error.message);
   }
});

/**
 * @description 添加商品到购物车的asyncThunk函数
 * */
export const addCartThunk: AsyncThunk<number, AddOrUpdateCartParams, AsyncThunkConfig> = createAsyncThunk("addCartThunk", async (addParams, { rejectWithValue }) => {
   try {
      const { data } = await addCartAPI(addParams);
      return data;
   } catch (error: any) {
      return rejectWithValue(error.message);
   }
});

/**
 * @description 更新购物车商品数量的asyncThunk函数
 * */
export const updateCartThunk: AsyncThunk<number, AddOrUpdateCartParams, AsyncThunkConfig> = createAsyncThunk("updateCartThunk:", async (updateParams, { rejectWithValue }) => {
   try {
      const { data } = await updateCartAPI(updateParams);
      return data;
   } catch (error: any) {
      return rejectWithValue(error.message);
   }
});

/**
 * @description 删除购物车商品的asyncThunk函数
 * */
export const deleteCartThunk: AsyncThunk<number, number[], AsyncThunkConfig> = createAsyncThunk("deleteCartThunk", async (cartIds, { rejectWithValue, dispatch }) => {
   try {
      const { data } = await deleteCartAPI(cartIds);
      dispatch(cartStore.actions.deleteGood(cartIds[0]));
      return data;
   } catch (error: any) {
      return rejectWithValue(error.message);
   }
});

const cartStore = createSlice({
   name: "homeStore",
   initialState,
   reducers: {
      changeCheckedAll(state: InitialState) {
         state.cartList.forEach(item => item.checked = !item.checked);
      },
      changeChecked(state: InitialState, action: ChangeCheckedActionType) {
         const { checked, goods_id } = action.payload;
         const currentGood: Cart = state.cartList.find(item => item.goods_id === goods_id) as Cart;
         currentGood.checked = checked;
      },
      deleteGood(state: InitialState, action: DeleteGoodActionType) {
         const cartList: Cart[] = state.cartList.filter(item => item.id !== action.payload);
         state.cartList = cartList;
      },
   },
   extraReducers(builder: ActionReducerMapBuilder<InitialState>) {
      builder.addCase(fetchCartListThunk.fulfilled, (state: InitialState, action: PayloadAction<CartResult>) => {
         const { list, cartTotal } = action.payload;
         state.cartTotal = cartTotal;
         state.cartList = list;
      });
   },
});

export const { changeCheckedAll, changeChecked, deleteGood } = cartStore.actions;
export default cartStore.reducer;
